#!/bin/bash

get_password() {
    # 循环直到密码不为空
    while true; do
        # 获取密码
        read -p "请输入密码：" password
        
        # 检查密码是否为空
        if [ -z "$password" ]; then
            echo "密码不能为空，请重新输入"
        else
            break
        fi
    done
}

if [ $# -eq 2 ]; then
    password=$2
else
    echo "请输入密码："
    read -s password
fi
# 调用函数获取密码
# get_password
set -e



rm -rf backend
mkdir -p backend/logs

# 打包镜像
sh ./build.sh $1

# docker save nest-api-image -o backend/nest-api-image.tar.gz

docker save nest-api-image:$1 | gzip > backend/nest-api-image.tar.gz

tag=$1
sed "s|tag|${tag}|g ; s|PASSWORD|${password}|g" docker-compose-server.yml > backend/docker-compose.yml

# sed "s|PASSWORD|${password}|g" docker-compose-server.yml > backend/docker-compose.yml



# echo "镜像压缩完成"
cp   r.sh   backend
# cp  -r src r.sh docker-compose.yml tsconfig.json  package*.json Dockerfile .development.env .dockerignore   backend

# 使用 Expect 执行登录并执行命令
expect <<-EOF
spawn scp -r -P 7758 backend root@121.4.60.15:/docker
set timeout -1
expect {
    "password:" {
        send "$password\r"
        exp_continue
    }
    "]#" {
        send "echo '上传完成' \n"
        send "exit \n"
        expect eof
    }
    "Permission denied" {
        puts "密码错误，请检查密码并重新运行脚本"
        exit 1
    }
    timeout {
        puts "连接超时，请检查网络连接并重新运行脚本"
        exit 1
    }
}
expect eof
EOF
rm -rf backend